<template>
  <div>
    <div class="ml-2 flex-1">
      <div>
        <a-card :bordered="false" style="height: 830px; width: 1380px">
          <a-form layout="inline" :model="searchForm" ref="searchFormRef">
            <a-form-item label="收费期" name="year">
              <a-date-picker v-model:value="searchForm.year" picker="year" />
            </a-form-item>
            <a-form-item label="收费状态" name="state">
              <a-select v-model:value="searchForm.state" :options="stateOptions" allow-clear placeholder="请选择收费状态"
                style="width: 150px" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="onSearch">
                查询
              </a-button>
              <a-button type="primary" style="margin-left: 10px" :icon="h(ReloadOutlined)" @click="onReset">
                重置
              </a-button>
              <a-button type="primary" style="margin-left: 10px" @click="onBatchStop">按选择停供</a-button>
              <a-button type="primary" style="margin-left: 10px" @click="onBatchSelectCondition">按查询条件停供</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data-source="dataSource" bordered :pagination="pagination" class="mt-5"
            :row-class-name="(_record: any, index: number) =>
                index % 2 === 1 ? 'table-striped' : null
              " :scroll="{ x: 1000, y: 550 }" :row-selection="{
              selectedRowKeys: RowKeys,
              onChange: onSelectChange,
            }" rowKey="areaID" />
        </a-card>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, h, ref } from 'vue';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { getValveManagementBatchApi } from '#/api/core/valveManagement';
import * as XLSX from 'xlsx';

import dayjs from 'dayjs';
const searchForm = reactive({
  year: '',
  state: undefined,
  stopType: undefined,
});
const searchFormRef = ref(null);
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const RowKeys = ref([]);
const columns = [
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '面积名称',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '停供开始时间',
    dataIndex: 'heatingStartDate',
    key: 'heatingStartDate',
    align: 'center',
  },
  {
    title: '停供结束时间',
    dataIndex: 'heatingEndDate',
    key: 'heatingEndDate',
    align: 'center',
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else {
    const query = {
      page: pagination.current,
      limit: pagination.pageSize,
      year: '',
      chargingStatus: '',
      treeData: props.selectedNodeId,
    };
    getValveManagementBatchApi(query).then((res: any) => {
      console.log(res);
      dataSource.value = res.data;
      pagination.total = res.total;
    });
  }

};
const onSelectChange = (selectedRowKeys: any) => {
  console.log('selectedRowKeys changed: ', selectedRowKeys);
  RowKeys.value = selectedRowKeys;
};
const onBatchStop = () => {
  if (RowKeys.value.length === 0) {
    message.error('请选择停供用户');
    return;
  } else {
    // 从表格数据中获取选中的用户并把areaID和year字段进行字符串拼接
    const selectedUsers = dataSource.value.filter((item: any) =>
      RowKeys.value.includes(item.areaID),
    );
    console.log(selectedUsers);
    const arr: any = [];
    selectedUsers.map((item: any) => arr.push(item.areaID + '-' + item.year));
    getValveManagementBatchSelectApi(arr.join(',')).then((res: any) => {
      console.log(res);
      if (res.data.code == 200) {
        message.success(res.data.msg);
        if (res.data.data.length > 0) {
          const header = [
            '住户名称',
            '热力卡号',
            '供暖年度',
            '停供原因',
            '停供错误原因',
            '供暖状态',
          ];
          const data = res.data.data.map((item: any) => [
            item.houseName,
            item.alipayConsNo,
            item.year,
            item.alterReason,
            item.errMsg,
            item.heatingStatus,
          ]);

          const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '批量停供失败数据');
          XLSX.writeFile(wb, '批量停供失败数据.xlsx');
        }
      }
    });
  }
};
const onBatchSelectCondition = () => {
  const query = {
    year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
    chargingStatus: '',
    treeData: props.selectedNodeId,
  };
  getValveManagementBatchSelectConditionApi(query).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      message.success(res.data.msg);
      if (res.data.data.length > 0) {
        const header = [
          '住户名称',
          '热力卡号',
          '供暖年度',
          '停供原因',
          '停供错误原因',
          '供暖状态',
        ];
        const data = res.data.data.map((item: any) => [
          item.houseName,
          item.alipayConsNo,
          item.year,
          item.alterReason,
          item.errMsg,
          item.heatingStatus,
        ]);

        const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '批量停供失败数据');
        XLSX.writeFile(wb, '批量停供失败数据.xlsx');
      }
    }
  });
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped></style>
